<template>
  <div class="suggest-container">
    <!-- 联想建议 -->
    <van-cell
      icon="search"
      v-for="(item,index) in suggestionText"
      :key="index"
      @click="$emit('search',item)"
    >
      <!-- 对关键字显示高亮 -->
      <div v-html="heightLigth(item)"></div>
    </van-cell>
  </div>
</template>
           
<script>
import { getSuggestion_api } from "@/api/search/index";
import _ from "lodash";
import { log } from "util";
export default {
  data() {
    return {
      suggestionText: ""
    };
  },
  props: {
    searchValue: {
      type: String,
      required: true
    }
  },
  watch: {
    //监听输入框数据变化,searchValue变化，就会触发
    //handler函数是固定写法
    searchValue: {
      //给输入框添加防抖---优化减少axios请求
      /*   handler(val) {
        this.getSuggestion(val)
      }, */
      handler: _.debounce(function(val) {
        this.getSuggestion(val);
        // console.log(val);
      }, 300),
      immediate: true // 该回调将会在侦听开始之后被立即调用(vue文档)
    }
  },
  methods: {
    //发送请求，获取联想数据-------------------------
    async getSuggestion(q) {
      const { data: res } = await getSuggestion_api(q);
      // console.log(res,454545)
      this.suggestionText = res.data.options;
    },
    //设置搜索结果高亮---------------------------
    //设置v-html 属性，添加类名，实现高亮
    heightLigth(dataStr) {
      //<span class="active">dataStr</span>,利用HTML标签replace替换原有的字符串
      //利用正则实力对象，可以替换全局的相同的字符串
      var reg = new RegExp(this.searchValue, "ig"); //ig 表示全局，不区分大小写
      return dataStr.replace(
        reg, `<span class="active">${this.searchValue}</span>`
      );
    }
  }
};
</script>
<style scoped lang="less">
.suggest-container {
  /deep/.active {
    color: orangered;
  }
}
</style>